package com.xexun.gpstracker.update;

/**
 * Created by Administrator on 2017/6/23.
 */
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.fix.grant.PermissionsManager;
import com.xexun.gpstracker.fix.grant.PermissionsResultAction;
import com.xexun.gpstracker.util.ApkUtil;
import com.xexun.gpstracker.util.CommUtil;
import com.xexun.gpstracker.util.HttpUtil;
import com.xexun.gpstracker.util.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;


public class UpdateManager {
    private String TAG = UpdateManager.class.getSimpleName();

    private Context mContext;

    //提示语
    private String updateMsg = "有最新的软件包哦，亲快下载吧~";

    //返回的安装包url
    private String apkUrl = null;

    private Dialog noticeDialog;

    private Dialog downloadDialog;
    /* 下载包安装路径 */
    private static final String savePath = "/sdcard/updatedemo/";

    private String saveFileName = null;

    /* 进度条与通知ui刷新的handler和msg常量 */
    private ProgressBar mProgress;


    private static final int DOWN_UPDATE = 1;

    private static final int DOWN_OVER = 2;

    private static final int SHOW_UPDATE = 3;

    private int progress;

    private Thread downLoadThread;

    private boolean interceptFlag = false;

    private Handler mHandler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE:
                    mProgress.setProgress(progress);
                    break;
                case DOWN_OVER:
                    installApk();
                    break;
                case  SHOW_UPDATE:
                    showNoticeDialog();
                default:
                    break;
            }
        };
    };



    public UpdateManager(Context context) {
        this.mContext = context;
        apkUrl = Utils.getMetaValue(mContext, "UPDATE_APK_URL");
//        saveFileName =Environment.getExternalStorageDirectory()+Utils.getMetaValue(mContext, "UPDATE_APK_NAME");
        saveFileName =savePath+Utils.getMetaValue(mContext, "UPDATE_APK_NAME");
        Log.i(UpdateManager.class.getSimpleName(),"apk_url = "+apkUrl);
        Log.i(UpdateManager.class.getSimpleName(),"saveFileName = "+saveFileName);
    }




    //外部接口让主Activity调用
    public void checkUpdateInfo(Context context) throws PackageManager.NameNotFoundException {
        PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        Constants.versionCode = info.versionCode;


        //在子线程中获取服务器的数据
        Thread thread = new Thread(){
            @Override
            public void run() {

                //1:确定地址
                try {

                  URL url = new URL(Constants.UPDATE_URL);

                    Log.d(TAG, "版本信息:"+ Constants.UPDATE_URL);

//                    URL url = new URL("http://120.25.75.101/apk/sifa.json");
                    URLConnection conn = url.openConnection();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.
                            getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while((line=reader.readLine())!=null){
                        sb.append(line);
                    }

                    JSONObject json = new JSONObject(sb.toString());
                    JSONObject jsonObject = json.getJSONObject("body");
                    int code = jsonObject.getInt("versionCode");
                    if (code != Constants.versionCode){
                        mHandler.sendEmptyMessage(SHOW_UPDATE);
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };

        //启动线程
        thread.start();


    }






    private void showNoticeDialog(){
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("软件版本更新");
        builder.setMessage(updateMsg);
        builder.setPositiveButton("下载", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                //权限校验
                PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult((Activity)mContext,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        new PermissionsResultAction() {
                            @Override
                            public void onGranted() {
                                showDownloadDialog();

                            }

                            @Override
                            public void onDenied(String permission) {
                                CommUtil.showMsgLong(String.format(mContext.getString(R.string.permission_refuse_comm_note), mContext.getString(R.string.permission_refuse_map_note)));
                            }
                        });

            }
        });
        builder.setNegativeButton("以后再说", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        noticeDialog = builder.create();
        noticeDialog.show();
    }

    private void showDownloadDialog(){
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("软件版本更新");

        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.progressbar, null);
        mProgress = (ProgressBar)v.findViewById(R.id.progress);

        builder.setView(v);
        builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true;
            }
        });
        downloadDialog = builder.create();
        downloadDialog.show();

        downloadApk();
    }

    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(apkUrl);

                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                File file = new File(savePath);
                if(!file.exists()){
                    file.mkdir();
                }
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do{
                    int numread = is.read(buf);
                    count += numread;
                    progress =(int)(((float)count / length) * 100);
                    //更新进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if(numread <= 0){
                        //下载完成通知安装
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf,0,numread);
                }while(!interceptFlag);//点击取消就停止下载.

                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch(IOException e){
                e.printStackTrace();
            }

        }
    };

    /**
     * 下载apk
     * @param
     */

    private void downloadApk(){
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }
    /**
     * 安装apk
     * @param
     */
    private void installApk(){
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }

        ApkUtil.installApk(apkfile);
//        Intent i = new Intent(Intent.ACTION_VIEW);
//        i.setDataAndType(getUriForFile(mContext,apkfile), "application/vnd.android.package-archive");
//        mContext.startActivity(i);

    }

    /**
     * 将文件转换成uri(支持7.0)
     *
     * @param mContext
     * @param file
     * @return
     */
    public static Uri getUriForFile(Context mContext, File file) {
        Uri fileUri = null;
        if (Build.VERSION.SDK_INT >= 24) {
            fileUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", file);
        } else {
            fileUri = Uri.fromFile(file);
        }
        return fileUri;
    }

}

